import axios from 'axios'
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

/**
 * @openapi
 * /api/accessToken:
 *   post:
 *     tags:
 *     - webhooks
 *     parameters:
 *     description: Access token
 *     responses:
 *       200:
 *         description: token信息
 */
export const query = async function (req, res, next) {
    try {
        const { code, installation_id } = req.query
        const url = 'https://api.atomgit.com/login/oauth/access_token'
        const data = {
            client_id: '6737f74274384078',
            client_secret: '44e25ece24ff496d8e15899d',
            code
        }

        axios.post(url, data).then(async response => {
            const {
                access_token,
                refresh_token,
            } = response.data

            await prisma.token.create({
                data: {
                    token: access_token,
                    refresh_token: refresh_token,
                    client_id: installation_id,
                }
            });
        }).catch(error => {
            console.error('Error:', error);
        });

        // return res.status(200).send({ data: 'success' });

        res.redirect('/');
    } catch (error) {
        debug(error);
        return res.status(501).send({
            message: error.meta?.cause || 'Error!'
        });
    }
}

